//
//  Location.m
//  huisaoche
//
//  Created by 谭伟 on 2017/7/2.
//  Copyright © 2017年 Minidai. All rights reserved.
//

#import "GpsManager.h"
#import "IpGpsModel.h"

@interface GpsManager()

@property(nonatomic, strong)CLGeocoder *geocoder;

@end

@implementation GpsManager

//+ (BOOL)cdm_isLocationServiceOpen
//{
//    if ([ CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
//        return NO;
//    } else
//        return YES;
//}

-(CLGeocoder *)geocoder
{
    if (!_geocoder) {
        _geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}

+ (GpsManager *)sharedGpsManager
{
    static GpsManager *instance = nil;
    static dispatch_once_t oneToken;
    
    dispatch_once(&oneToken, ^{
        
        instance = [[GpsManager alloc] init];
    });
    
    return instance;
}

- (id)init {
    self = [super init];
    if (self) {
        // 打开定位 然后得到数据
        
        _manager = [[CLLocationManager alloc] init];
        _manager.delegate = self;
        //_manager.desiredAccuracy = kCLLocationAccuracyBest;
        _manager.desiredAccuracy = kCLLocationAccuracyKilometer;
        _manager.distanceFilter = 1000;

        if ([_manager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [_manager requestWhenInUseAuthorization];
            //[_manager requestAlwaysAuthorization];
        }
    }
    return self;
}

- (void)getCurrentCity
{
    
    //根据IP获取当前地址
    [self loadGpsData];
//    [NetworkProgressHUD hideHud];
//    // 停止上一次的
//    [_manager stopUpdatingLocation];
//    // 开始新的数据定位
//    [_manager startUpdatingLocation];
}

- (void)loadGpsData {
    NSString *urlstring = @"http://ip.taobao.com/service/getIpInfo2.php?ip=myip";

    NSURL *url = [NSURL URLWithString:urlstring];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        IpGpsModel *model = [IpGpsModel new];
        if (str && str.length > 0) {
            model = [IpGpsModel mj_objectWithKeyValues:str];
        }
        
        NSString *cityStr = @"";
        if ([model.data.city containsString:@"市"]) {
            cityStr = [model.data.city stringByReplacingOccurrencesOfString:@"市" withString:@""];
        }
        
        if (cityStr.length <= 0) {
            cityStr = @"深圳";
        }
        NSString *provinceStr = model.data.region;
        if(provinceStr.length <= 0) {
            provinceStr = @"广东";
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"GPS_Location" object:nil userInfo:@{@"provinceName":provinceStr,@"cityName":cityStr}];
        });
        NSLog(@"%@",str);
    }];
    [dataTask resume];
}


- (void)stopLocation {
    
    [_manager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation *location = [locations lastObject];
   // NSLog(@"%zd",location.coordinate);

    // 反向地理编译出地址信息
    [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (!error)
        {
            if ([placemarks count] > 0) {

                CLPlacemark *placemark = [placemarks firstObject];
               // NSLog(@"placemark-----%@",placemark);
                NSLog(@"placemark.city-----%@",placemark.locality);

                // 获取城市
                NSString *pronvince = placemark.administrativeArea;
                NSString *city = placemark.locality;
                if (!city.length) {
                    // 6
                    [GpsManager sharedGpsManager].cityName = @"深圳";
                }

                else {
                    [GpsManager sharedGpsManager].cityName = city;
                    [GpsManager sharedGpsManager].provinceName = pronvince;

                }


              //  NSLog(@"self.cityName---%@",[GpsManager sharedGpsManager].cityName);

            } else if ([placemarks count] == 0) {


                [GpsManager sharedGpsManager].cityName = @"深圳";
            }
        }
        else
        {
            [GpsManager sharedGpsManager].cityName = @"深圳";
        }

        //        [[CKGpsManager sharedGpsManager] stop];
        //1.这种是在需要的时候用，和下面NSUserDefaults 看自己的需求来用.
        NSString *provinceName = [[GpsManager sharedGpsManager].provinceName stringByReplacingOccurrencesOfString:@"省" withString:@""];
        if (provinceName.length <= 0) {
            provinceName = @"广东";
        }
        NSString *cityName = [[GpsManager sharedGpsManager].cityName stringByReplacingOccurrencesOfString:@"市" withString:@""];
        if (cityName.length <= 0) {
            cityName = @"深圳";
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"GPS_Location" object:nil userInfo:@{@"provinceName":provinceName,@"cityName":cityName}];


        NSString *tmpCity = [GpsManager sharedGpsManager].cityName;
//        tmpCity = [tmpCity stringByReplacingOccurrencesOfString:@"市" withString:@""];

        //保存当前位置信息
        if (!tmpCity.length) {
            tmpCity = @"深圳";
        }
        //2.这种是在首页或者启动的时候用.
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:tmpCity forKey:@"CurrentCityKey"];
        [defaults synchronize];
    }];

    [self.manager stopUpdatingLocation];
    
}


@end
